<template>
    <div
        class="PhotoAlbum"
        :style="{
            backgroundImage: `url('${PageAssets.bookBg}')`,
            backgroundSize: 'cover',
        }"
    >
        <!-- <button
            @click="devMode = !devMode"
            style="position: fixed; top: 10px; left: 10px; z-index: 999"
        >
            {{ devMode ? "关闭开发者模式" : "开启开发者模式" }}
        </button> -->
        <button
            v-if="devMode"
            @click="exportPositions"
            style="position: fixed; top: 50px; left: 10px; z-index: 999"
        >
            导出位置数据
        </button>
        <div
            v-for="(character, idx) in characterData"
            :key="character.id"
            class="book"
            :class="{ bigBook: character.isZoomed }"
            :style="getBookStyle(character, idx)"
            @mouseenter="hoverBook(character)"
            @mouseleave="resetBook(character)"
            @mousedown="devMode ? startDrag($event, idx) : null"
            @click="handleBookClick(character, idx, $event)"
            ref="bookRefs"
        >
            <div
                class="front"
                :class="{
                    'left-center': character.transformOrigin === 'left center',
                    'right-center':
                        character.transformOrigin === 'right center',
                }"
                :style="getfrontStyle(character)"
            >
                <div class="front-1">
                    <img
                        v-if="character.isAvatar"
                        class="avatar"
                        :src="character.avatar"
                        :style="{
                            top: character.avatarTop + '%',
                            left: character.avatarLeft + '%',
                        }"
                        alt="头像"
                    />
                    <div class="name">{{ character.name }}</div>
                    <img
                        class="front-1-bg"
                        :src="character.bookfront1"
                        alt="封面-正面"
                    />
                </div>
                <div class="front-2">
                    <img
                        class="front-2-bg"
                        :src="character.bookfront2"
                        alt="封面-背面"
                    />
                    <div class="desc" :style="getDescStyle(character, idx)">
                        {{ character.desc }}
                    </div>
                </div>
            </div>
            <div
                v-for="n in character.essay.length"
                :key="n"
                class="page"
                :style="{
                    transformOrigin: character.transformOrigin,
                    transform:
                        character.currentPage >= n
                            ? character.transformOrigin == 'left center'
                                ? `rotateY(${-174 + n}deg) scale(1.1)`
                                : `rotateY(${174 - n}deg) scale(1.1)`
                            : character.transformOrigin == 'left center'
                            ? `rotateY(${-15 + n}deg) scale(1.1)`
                            : `rotateY(${15 - n}deg) scale(1.1)`,
                    zIndex: 9 - n,
                }"
                @click.stop="handlePageClick(character, n)"
                @click="handleBookClick(character, idx, $event)"
            >
                <div class="page-1" :style="getPageStyle(character, idx, n)">
                    <img
                        class="page-1-bg"
                        :src="character.bookPage1"
                        alt="内容页-正面"
                    />
                    <div class="essay essay-1">
                        <div
                            class="Bigimg"
                            v-if="
                                character.essay[n - 1].frontContent[0].type ==
                                'img2'
                            "
                        >
                            <img
                                :src="
                                    character.essay[n - 1].frontContent[0].Image
                                "
                                alt="内容页图片"
                            />
                        </div>
                        <div
                            class="Bigimg3"
                            v-else-if="
                                character.essay[n - 1].frontContent[0].type ==
                                'img3'
                            "
                        >
                            <img
                                :src="
                                    character.essay[n - 1].frontContent[0].Image
                                "
                                alt="内容页图片"
                            />
                        </div>
                        <div v-else>
                            <div class="essay-Content frontContent-1">
                                <img
                                    v-if="
                                        character.essay[n - 1].frontContent[0]
                                            .type == 'img'
                                    "
                                    :src="
                                        character.essay[n - 1].frontContent[0]
                                            .Image
                                    "
                                    alt="内容页图片"
                                />
                                <div v-else class="text">
                                    {{
                                        character.essay[n - 1].frontContent[0]
                                            .text
                                    }}
                                </div>
                            </div>
                            <div class="essay-Content frontContent-2">
                                <img
                                    v-if="
                                        character.essay[n - 1].frontContent[1]
                                            .type == 'img'
                                    "
                                    :src="
                                        character.essay[n - 1].frontContent[1]
                                            .Image
                                    "
                                    alt="内容页图片"
                                />
                                <div v-else class="text">
                                    {{
                                        character.essay[n - 1].frontContent[1]
                                            .text
                                    }}
                                </div>
                            </div>
                            <div class="essay-Content frontContent-3">
                                <img
                                    v-if="
                                        character.essay[n - 1].frontContent[2]
                                            .type == 'img'
                                    "
                                    :src="
                                        character.essay[n - 1].frontContent[2]
                                            .Image
                                    "
                                    alt="内容页图片"
                                />
                                <div v-else class="text">
                                    {{
                                        character.essay[n - 1].frontContent[2]
                                            .text
                                    }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <p class="PagesNume-1">
                        {{ character.essay[n - 1].PagesNume[0] }}
                    </p>
                </div>
                <div class="page-2" :style="getPageStyle(character, idx, n)">
                    <img
                        class="page-2-bg"
                        :src="character.bookPage2"
                        alt="内容页-背"
                    />
                    <div class="essay essay-2">
                        <div
                            class="Bigimg"
                            v-if="
                                character.essay[n - 1].backContent[0].type ==
                                'img2'
                            "
                        >
                            <img
                                :src="
                                    character.essay[n - 1].backContent[0].Image
                                "
                                alt="内容页图片"
                            />
                        </div>
                        <div
                            class="Bigimg3"
                            v-else-if="
                                character.essay[n - 1].backContent[0].type ==
                                'img3'
                            "
                        >
                            <img
                                :src="
                                    character.essay[n - 1].backContent[0].Image
                                "
                                alt="内容页图片"
                            />
                        </div>
                        <div v-else>
                            <div class="essay-Content backContent-1">
                                <img
                                    v-if="
                                        character.essay[n - 1].backContent[0]
                                            .type == 'img'
                                    "
                                    :src="
                                        character.essay[n - 1].backContent[0]
                                            .Image
                                    "
                                    alt="内容页图片"
                                />
                                <div v-else class="text">
                                    {{
                                        character.essay[n - 1].backContent[0]
                                            .text
                                    }}
                                </div>
                            </div>
                            <div class="essay-Content backContent-2">
                                <img
                                    v-if="
                                        character.essay[n - 1].backContent[1]
                                            .type == 'img'
                                    "
                                    :src="
                                        character.essay[n - 1].backContent[1]
                                            .Image
                                    "
                                    alt="内容页图片"
                                />
                                <div v-else class="text">
                                    {{
                                        character.essay[n - 1].backContent[1]
                                            .text
                                    }}
                                </div>
                            </div>
                            <div class="essay-Content backContent-3">
                                <img
                                    v-if="
                                        character.essay[n - 1].backContent[2]
                                            .type == 'img'
                                    "
                                    :src="
                                        character.essay[n - 1].backContent[2]
                                            .Image
                                    "
                                    alt="内容页图片"
                                />
                                <div v-else class="text">
                                    {{
                                        character.essay[n - 1].backContent[2]
                                            .text
                                    }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <p class="PagesNume-2">
                        {{ character.essay[n - 1].PagesNume[1] }}
                    </p>
                </div>
            </div>
            <div class="back" :style="getbackStyle(character)">
                <img class="back-bg" :src="character.bookBack" alt="封底" />
            </div>
        </div>
        <div v-if="showExport" class="export-modal">
            <textarea
                readonly
                :value="exportText"
                style="width: 100%; height: 200px"
            ></textarea>
            <button @click="showExport = false">关闭</button>
        </div>
        <navigationBig :top="'0px'" :right="'1%'" />
    </div>
</template>

<script setup>
// --------------------
// 1. 导入依赖
// --------------------
import { onMounted, onUnmounted, ref, nextTick, onBeforeUnmount } from "vue";
import navigationBig from "@/components/navigationBig.vue";
import { useRouter } from "vue-router";
// import data from "./Photo-data.js";
import { getBookData, getPageAssets } from "./api";
const router = useRouter();
const PageAssets = ref("");
function handleWheel(e) {
    if (e.deltaY < 0) {
        router.push("/video-player");
    }
    if (e.deltaY > 0) {
        router.push("/characters");
    }
}
// --------------------
// 2. 响应式数据定义
// --------------------

// 开发者模式开关
const devMode = ref(false);
// 导出弹窗相关
const showExport = ref(false);
const exportText = ref("");
// 拖拽相关数据
const dragInfo = ref({
    idx: null,
    startX: 0,
    startY: 0,
    startTop: 0,
    startLeft: 0,
});
// 放大书本相关数据
const zoomedIdx = ref(null); // 当前放大书本的索引
const zoomAnim = ref({}); // 放大动画参数
const bookRefs = ref([]); // 书本DOM引用（未实际使用）

// 角色数据
const characterData = ref([]);

// --------------------
// 3. 书本悬停与恢复
// --------------------

// 鼠标悬停时，调整书本旋转角度
function hoverBook(character) {
    if (character.transformOrigin === "left center") {
        character._rotateY = 10;
        character._rotateX = 0;
    } else {
        character._rotateY = 1;
        character._rotateX = 0;
    }
}

// 鼠标离开时，恢复书本初始旋转角度和页码（未放大时才恢复）
function resetBook(character) {
    if (!character.isZoomed) {
        character._rotateY = character.rotateY;
        character._rotateX = character.rotateX;
        character.currentPage = 0;
    }
}

// --------------------
// 4. 书本翻页逻辑
// --------------------

// 只有放大状态下允许翻页
function handlePageClick(character, n) {
    if (!character.isZoomed) return;
    if (n <= character.currentPage) {
        character.currentPage = n - 1;
    } else {
        character.currentPage = n;
    }
}

// --------------------
// 5. 书本拖拽（开发者模式）
// --------------------

// 鼠标按下，开始拖拽
function startDrag(e, idx) {
    if (!devMode.value) return;
    dragInfo.value = {
        idx,
        startX: e.clientX,
        startY: e.clientY,
        startTop: parseFloat(characterData.value[idx].bookTop),
        startLeft: parseFloat(characterData.value[idx].bookLeft),
    };
    document.addEventListener("mousemove", onDrag);
    document.addEventListener("mouseup", stopDrag);
}

// 拖拽过程中，更新书本位置
function onDrag(e) {
    const { idx, startX, startY, startTop, startLeft } = dragInfo.value;
    if (idx === null) return;
    const rem = 16;
    const deltaX = (e.clientX - startX) / rem;
    const deltaY = (e.clientY - startY) / rem;
    characterData.value[idx].bookLeft = Math.max(
        0,
        Math.round(startLeft + deltaX)
    );
    characterData.value[idx].bookTop = Math.max(
        0,
        Math.round(startTop + deltaY)
    );
}

// 拖拽结束，移除事件监听
function stopDrag() {
    dragInfo.value.idx = null;
    document.removeEventListener("mousemove", onDrag);
    document.removeEventListener("mouseup", stopDrag);
}

// --------------------
// 6. 书本放大动画与居中
// --------------------

// 计算书本样式（普通/放大/动画阶段）
function getBookStyle(character, idx) {
    const transition = "transition: all 4s cubic-bezier(.4,0,.2,1);";
    if (
        character.isZoomed &&
        zoomAnim.value.idx === idx &&
        zoomAnim.value.animating
    ) {
        // 动画阶段：用 fixed 定位，原始位置和尺寸
        return `position:fixed;top:${zoomAnim.value.top}px;left:${
            zoomAnim.value.left
        }px;width:${zoomAnim.value.width}px;height:${
            zoomAnim.value.height
        }px;z-index:1000;transform:rotateY(${
            character._rotateY
        }deg) rotateX(${-character._rotateX}deg);${transition}`;
    }
    if (character.isZoomed) {
        // 居中阶段：居中显示，宽高变大
        if (character.transformOrigin === "left center") {
            return `position:fixed;top:50%;left:50%;width:37.5rem;height:56.25rem;z-index:1000;transform:translate(-40%, -50%) rotateY(${
                character._rotateY
            }deg) rotateX(${-character._rotateX}deg);${transition}`;
        } else {
            return `position:fixed;top:50%;left:50%;width:37.5rem;height:56.25rem;z-index:1000;transform:translate(-100%, -50%) rotateY(0deg) rotateX(0deg);${transition}`;
        }
    }
    // 普通状态
    return `top: ${character.bookTop}rem; left: ${
        character.bookLeft
    }rem; width: 7.5rem;height: 11.25rem;transform:rotateY(${
        character._rotateY
    }deg) rotateX(${-character._rotateX}deg);${transition}`;
}
// 计算封面背页字体样式（普通/放大）
function getDescStyle(character, idx) {
    let DescStyle = `
        display: flex;
        flex-direction: column;
        justify-content: center;
        height: 100%;
        padding: 5%;
        writing-mode: vertical-rl;
        color:${character.color};
        transition: font-size 4s cubic-bezier(.4,0,.2,1);`;
    if (character.transformOrigin == "left center") {
        if (character.isZoomed) {
            // 放大
            return DescStyle + `font-size: 4.8rem;left: 0;`;
        }
        // 普通状态
        return DescStyle + `font-size: 1rem;left: 0;`;
    } else {
        if (character.isZoomed) {
            // 放大
            return DescStyle + `font-size: 4.8rem;right: 0;`;
        }
        // 普通状态
        return DescStyle + `font-size: 1rem;right: 0;`;
    }
}
// 计算内容页字体样式（普通/放大）
function getPageStyle(character, idx, n) {
    let PageStyle = `
        color:${character.color};
        font-weight: 700;
        transition: font-size 4s cubic-bezier(.4,0,.2,1);
        `;

    if (n != undefined) {
        if (character.essay[n - 1].frontContent[0].type == "img3") {
            // 如果是大图类型，去掉padding
            PageStyle += `padding: 0;`;
            if (character.isZoomed) {
                // 放大
                return (
                    ` 
        font-size: 1.8rem;` + PageStyle
                );
            }
            // 普通状态
            return (
                `
        font-size: 0.36rem;` + PageStyle
            );
        } else {
            // 普通内容页有padding
            PageStyle += `padding: 5%;`;
            if (character.isZoomed) {
                // 放大
                return (
                    ` 
        font-size: 1.8rem;` + PageStyle
                );
            }
            // 普通状态
            return (
                `
        font-size: 0.36rem;` + PageStyle
            );
        }
    }
}
function getbackStyle(character) {
    if (character.transformOrigin === "left center") {
        return {
            transformOrigin: character.transformOrigin,
            transform: `rotateY(${character.essay.length - 10}deg) scale(1.1)`,
        };
    } else if (character.transformOrigin === "right center") {
        return {
            transformOrigin: character.transformOrigin,
            transform: `rotateY(${character.essay.length + 5}deg) scale(1.1)`,
        };
    }
    return { transformOrigin: character.transformOrigin };
}
// 书本点击：首次点击放大，后续允许翻页
function handleBookClick(character, idx, e) {
    if (devMode.value) return;
    if (!character.isZoomed) {
        // 放大动画准备
        character.isZoomed = true;
        zoomedIdx.value = idx;
        nextTick(() => {
            const el = document.querySelectorAll(".book")[idx];
            const rect = el.getBoundingClientRect();
            zoomAnim.value = {
                idx,
                top: rect.top,
                left: rect.left,
                width: rect.width,
                height: rect.height,
                animating: true,
            };
            // 下一帧切换到居中
            requestAnimationFrame(() => {
                zoomAnim.value = { ...zoomAnim.value, animating: false };
            });
            // 监听全局点击，点击外部恢复
            document.addEventListener("mousedown", handleGlobalClick);
        });
        e.stopPropagation();
    }
    // 放大状态下允许翻页（由 handlePageClick 控制）
}

// 全局点击事件：点击放大书本外部时恢复
function handleGlobalClick(e) {
    if (zoomedIdx.value === null) return;
    const el = document.querySelectorAll(".book")[zoomedIdx.value];
    if (!el.contains(e.target)) {
        const character = characterData.value[zoomedIdx.value];
        character.isZoomed = false;
        character.currentPage = 0;
        character._rotateY = character.rotateY;
        character._rotateX = character.rotateX;
        zoomedIdx.value = null;
        zoomAnim.value = {};
        document.removeEventListener("mousedown", handleGlobalClick);
    }
}

// 生命周期清理：组件卸载时移除全局事件
onBeforeUnmount(() => {
    document.removeEventListener("mousedown", handleGlobalClick);
});

// --------------------
// 7. 导出位置数据（开发者模式）
// --------------------

// 导出所有角色的位置信息，格式与 characterData 一致
function exportPositions() {
    const arr = characterData.value.map((c) => ({
        id: c.id,
        bookTop: c.bookTop,
        bookLeft: c.bookLeft,
    }));
    exportText.value = arr
        .map((obj) => {
            return `${obj.id}:{bookTop: ${obj.bookTop},bookLeft: ${obj.bookLeft},},`;
        })
        .join("\n");
    showExport.value = true;
}

// --------------------
// 8. .front动态transform（封面翻页动画）
// --------------------

// 翻页后或放大时，封面始终保持翻开的状态
function getfrontStyle(character) {
    if (character.currentPage > 0) {
        if (character.transformOrigin === "left center") {
            return {
                transformOrigin: character.transformOrigin,
                transform: "rotateY(-175deg) scale(1.1)",
            };
        } else {
            return {
                transformOrigin: character.transformOrigin,
                transform: "rotateY(175deg) scale(1.1)",
            };
        }
    }
    if (character.isZoomed) {
        if (character.transformOrigin === "left center") {
            return {
                transformOrigin: character.transformOrigin,
                transform: "rotateY(-175deg) scale(1.1)",
            };
        } else {
            return {
                transformOrigin: character.transformOrigin,
                transform: "rotateY(175deg) scale(1.1)",
            };
        }
    }
    // 默认样式
    return { transformOrigin: character.transformOrigin };
}
// 页面挂载时请求数据
onMounted(async () => {
    window.addEventListener("wheel", handleWheel);
    try {
        const data = await getBookData();
        // 初始化每个角色的页面状态字段
        characterData.value = data.map((item) => ({
            ...item,
            currentPage: 0,
            _rotateY: item.rotateY,
            _rotateX: item.rotateX,
            isZoomed: false,
        }));
    } catch (e) {
        console.error("获取角色数据失败", e);
    }
    PageAssets.value = await getPageAssets();
});
onUnmounted(() => {
    window.removeEventListener("wheel", handleWheel);
});
</script>

<style lang="scss" scoped>
.PhotoAlbum {
    position: relative;
    height: 100vh;
    perspective: 1200px;

    .book {
        transform-style: preserve-3d;
        position: absolute;
        cursor: pointer;
        margin: 1.25rem;
        transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);
        // 开发者模式下可拖拽
        &:active {
            z-index: 999;
            box-shadow: 0 0 0.625rem #00f;
        }
        .front,
        .page,
        .back {
            transform-style: preserve-3d;
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            border-bottom-right-radius: 0.5em;
            border-top-right-radius: 0.5em;
            background: #f5f5f5;
            transition: transform 1s, box-shadow 0.35s;
            z-index: 1;
        }

        .front {
            z-index: 10;
            background: #fff;
            // 不需要再写 hover transform，交由 getfrontStyle 控制
            .front-1,
            .front-2 {
                position: absolute;
                width: 100%;
                height: 100%;
                backface-visibility: hidden;
                top: 0;
                left: 0;
            }
            .front-1 {
                .avatar {
                    position: absolute;
                    transform: translateX(-50%);
                    width: 40%;
                }
                .name {
                    position: absolute;
                    top: 50%;
                    width: 100%;
                    text-align: center;
                    color: #000000;
                    font-weight: bold;
                    text-shadow: 0 0 1px #000000, 0 0 1px #000000,
                        0 0 2px #ffffff, 0 0 2px #ffffff, 0 0 2px #ffffff,
                        0 0 2px #ffffff;
                }
                .front-1-bg {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    z-index: 1;
                }
            }
            .front-2 {
                transform: rotateY(180deg);
                background: #57572a;
                display: flex;
                align-items: center;
                justify-content: center;
                .front-2-bg {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    z-index: 1;
                }
                .desc {
                    position: absolute;
                    top: 0;
                }
            }
        }
        .front.left-center {
            transform: rotateY(-16deg) scale(1.1);
        }
        .front.right-center {
            transform: rotateY(16deg) scale(1.1);
        }
        .page-1,
        .page-2 {
            position: absolute;
            width: 100%;
            height: 100%;
            padding: 5%;
            backface-visibility: hidden;
            overflow: hidden;
            top: 0;
            left: 0;
        }
        .page-1 {
            .page-1-bg {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                object-fit: cover;
                z-index: 1;
            }
            .PagesNume-1 {
                position: absolute;
                bottom: 0;
                right: 0;
            }
        }
        .page-2 {
            transform: rotateY(180deg);
            .page-2-bg {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                object-fit: cover;
                z-index: 1;
            }
            .PagesNume-2 {
                position: absolute;
                bottom: 0;
                left: 0;
            }
        }
        .essay {
            height: 100%;
            .Bigimg {
                height: 100%;
                width: 100%;
                overflow: hidden;
                img {
                    height: 100%;
                }
            }
            .Bigimg3 {
                height: 100%;
                width: 100%;
                img {
                    width: 100%;
                }
            }
            .essay-Content {
                width: 100%;
                height: 31%;
                margin-bottom: 2%;
                overflow: hidden;
                text-shadow: 0 0 2px #000, 0 0 4px #ffffff;
                img {
                    width: 100%;
                }
            }
        }
        .back {
            z-index: 20;
            background: #fff;
            .back-bg {
                width: 100%;
                height: 100%;
            }
        }
        &:hover {
            .front.left-center {
                transition: all 1.5s;
                transform: rotateY(-132deg) scale(1.1);
            }
            .front.right-center {
                transition: all 1.5s;
                transform: rotateY(150deg) scale(1.1);
            }
        }
    }
    .desc,
    .essay-Content {
        transition: font-size 4s cubic-bezier(0.4, 0, 0.2, 1);
        will-change: font-size;
    }
    .export-modal {
        position: fixed;
        top: 100px;
        left: 10px;
        width: 400px;
        background: #fff;
        border: 1px solid #ccc;
        z-index: 1000;
        padding: 10px;
        box-shadow: 0 0 10px #aaa;
    }
}
</style>